<template>
  <div class="app-container">
    <el-table
      :key="tableKey"
      v-loading="tableLoading"
      :data="files"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="文件名" prop="fileName" min-width="90"></el-table-column>
      <el-table-column label="大小" min-width="120" align="center">
        <template slot-scope="{row}">
          {{row.size}}KB
        </template>
      </el-table-column>
      <el-table-column label="修改时间" align="center" min-width="160">
        <template slot-scope="scope">
          <span>{{ scope.row.time ? transDate(scope.row.time) : ''}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="90" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button size="mini" type="danger" @click="downloadFile(row.fileName)">下载</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
  import {
    getFileList,
    downloadFile
  } from "@/api/fileDownload";
  import _ from "lodash";
  import moment from "moment";

  export default {
    components: {
    },
    data() {
      return {
        isSubmitLoading: false,
        downloadLoading: false,
        tableLoading: false,
        tableKey: 0,
        files: [],
        totalCount: 0
      };
    },
    computed: {},
    watch: {},
    created() {
      this.getFileList();
    },
    methods: {
      selectionChange(selection) {
        this.itemsChecked = selection;
      },
      getFileList() {
        getFileList().then(result => {
          this.files = result;
          this.tableLoading = false;
        });
      },
      downloadFile(name) {
        this.downloadLoading = true;
        downloadFile(name).then(result => {
          this.download(result, name);
        });
      },
      download(data, name) {
        const blob = new Blob([data]);
        const fileName = name;
        if ('download' in document.createElement('a')) { // 非IE下载
          const elink = document.createElement('a');
          elink.download = fileName;
          elink.style.display = 'none';
          elink.href = URL.createObjectURL(blob);
          document.body.appendChild(elink);
          elink.click();
          URL.revokeObjectURL(elink.href); // 释放URL 对象
          document.body.removeChild(elink);
        } else { // IE10+下载
          navigator.msSaveBlob(blob, fileName);
        }
        this.downloadLoading = false;
      },
      transDate(timestamp) {
        return moment(timestamp * 1000).format("YYYY-MM-DD HH:mm:ss");
      }
    }
  };
</script>

<style lang="scss">
  .el-table .danger-row {
    color: #F56C6C !important;
  }
</style>
